<template>
  <div>
    <NavBar @show-modal="showModal" :user="user" @clean:user="user ={}"/>
    <div class="main-content">
      <div class="sidebar">
        <CategoryFilter
            @category-selected="handleCategorySelect"
            @subcategory-selected="handleSubCategorySelect"
        />
        <PriceFilter @price-filter="handlePriceFilter"/>
        <BrandFilter @brand-filter-applied="handleBrandFilter"/>
      </div>

      <div class="product-area">
        <SearchBox @search="searchByKeyword"></SearchBox>
        <ProductToolbar
            @sort-changed="handleSortChange"
            @view-changed="handleViewChange"
        />
        <ProductGrid :products="productList"/>
        <Pagination
            :current-page="currentPage"
            :total-pages="totalPages"
            @page-changed="handlePageChange"
        />
      </div>
    </div>
    <Footer></Footer>
    <Modal :is-visible="modalConfig.visible" @close-modal="closeModal">
      <Login v-if="1==modalConfig.type" @show-modal="showModal"></Login>
      <Register v-else-if="2==modalConfig.type" @show-modal="showModal"></Register>
      <FindPassword v-else-if="3==modalConfig.type" @show-modal="showModal"></FindPassword>
      <div v-else>
        <span style="color:red">模态框类型错误</span>
      </div>
    </Modal>
  </div>
</template>

<script setup>
import {ref, reactive, toRaw, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import NavBar from '@views/common/NavBar.vue'
import Footer from "@views/common/Footer.vue";
import BrandFilter from "@views/product/search/BrandFilter.vue";
import CategoryFilter from "@views/product/search/CategoryFilter.vue";
import PriceFilter from "@views/product/search/PriceFilter.vue";
import ProductToolbar from "@views/product/search/ProductToolbar.vue";
import ProductGrid from "@views/product/search/ProductGrid.vue";
import Pagination from "@views/common/Pagination.vue";
import SearchBox from '@views/product/SearchBox.vue'
import Register from "@views/Register.vue";
import FindPassword from "@views/FindPassword.vue";
import Modal from "@views/common/Modal.vue";
import Login from "@views/Login.vue"
import apis, {IMG_BASE_PATH} from "@/config/api-config.js";
import getResponse from "@assets/js/http-client.js";
const user = ref({});

// 商品列表数据
const productList = ref([])

// 分页相关数据
const currentPage = ref(1)
const totalPages = ref(1)

// 搜索条件状态
const searchCriteria = reactive({
  pageNum: 1,
  pageSize: 9,
  keyword: '',
  categoryId: null,
  subCategoryId: null,
  minPrice: null,
  maxPrice: null,
  brandId: null,
  orderFields: null,
  orderTypes: null,
  viewMode: 'grid'
})

// 处理分类选择
const handleCategorySelect = async (category) => {
  searchCriteria.categoryId = category;
  searchCriteria.subCategoryId = null;
  searchCriteria.pageNum = 1;
  currentPage.value = 1;
  await searchProductList();
}

// 处理子分类选择
const handleSubCategorySelect = async (subCategory) => {
  searchCriteria.subCategoryId = subCategory
  searchCriteria.pageNum = 1;
  currentPage.value = 1;
  await searchProductList();
}

// 处理价格筛选
const handlePriceFilter = async (priceRange) => {
  //将当前页设置为1
  searchCriteria.pageNum = 1;
  currentPage.value = 1;
  // 清空之前的价格筛选条件
  searchCriteria.minPrice = null;
  searchCriteria.maxPrice = null;
  const minPrice = priceRange.min;
  const maxPrice = priceRange.max;
  if (minPrice) {
    searchCriteria.minPrice = 100 * minPrice;
  }
  if (maxPrice) {
    searchCriteria.maxPrice = 100 * maxPrice;
  }
  await searchProductList();
}

// 处理品牌筛选
const handleBrandFilter = (brand) => {
  searchCriteria.brand = brand
  // 这里可以调用API重新获取产品数据
  console.log('品牌筛选:', brand)
}

// 处理排序变化
const handleSortChange = async (sortOption) => {
  if ('default' === sortOption) {
    searchCriteria.orderFields = null;
    searchCriteria.orderTypes = null;
  } else {
    let orderFields = sortOption.split('_')[0];
    let orderTypes = sortOption.split('_')[1];
    searchCriteria.orderFields = orderFields;
    searchCriteria.orderTypes = orderTypes;
  }
  await searchProductList();
}

// 处理视图变化
const handleViewChange = (viewMode) => {
  searchCriteria.viewMode = viewMode
  console.log('视图变化:', viewMode)
}

// 处理分页变化
const handlePageChange = async (page) => {
  currentPage.value = page
  searchCriteria.pageNum = page;
  await searchProductList();
}

//模态框信息
const modalConfig = reactive({
  visible: false,
  //1:显示会员登录模态框;2:显示会员注册模态框;3:显示找回密码或忘记密码模态框
  type: 1
});
//关闭模态框
const closeModal = () => {
  modalConfig.visible = false;
  modalConfig.type = 1;//默认显示登录模态框
}
//打开模态框
const showModal =async (type) => {
  if (!(1 === type || 2 === type || 3 === type || 0 === type)) {
    ElMessage({
      message: '打开模态框失败,未知的页面',
      type: 'error',
      duration: 2000
    });
    return;
  }
  //0表示登录成功后,关闭登录框
  if (0 === type) {
    closeModal();
    //登录成功后，获取用户信息
    await getUserInfo();
    return;
  }
  modalConfig.type = type;
  modalConfig.visible = true;
}
/**
 * 商品搜索
 * @returns {Promise<void>}
 */
const searchProductList = async () => {
  let url = apis.product.productList.url;
  let type = apis.product.productList.type;
  let params = {};
  let criteria = {...toRaw(searchCriteria)}
  for (let key in criteria) {
    let value = criteria[key];
    if (criteria[key] != null) {
      params[key] = value;
    }
  }
  console.info(params)
  let result = await getResponse(url, type, params);
  if (200 != result.code) {
    ElMessage.error(result.message);
    return;
  }
  productList.value = result.data.records;
  //设置分页参数:当前页、总页数
  totalPages.value = result.data.pages;
  currentPage.value = result.data.current;
}
const searchByKeyword = async (keyword) => {
  //从第1页开始搜索
  searchCriteria.pageNum = 1;
  currentPage.value = 1;
  searchCriteria.keyword = keyword;
  await searchProductList();
}
onMounted(async () => {
  await searchProductList();
  await getUserInfo();
});
const getUserInfo = async () => {
  let token = localStorage.getItem('wemall-token');
  if (token === null) {
    return;
  }
  //如果有token,说明已登录过系统,则根据token获取用户数据
  let url = apis.member.getInfo.url;
  let type = apis.member.getInfo.type;
  //token参数已统一处理,无需再手动添加
  const result = await getResponse(url, type);
  if (200 !== result.code) {
    console.info('获取用户信息失败:', result.message);
    return;
  }
  //console.info('获取用户信息成功:', result.data);
  user.value = result.data;
  let avatar = user.value.avatar;
  if (!avatar) {
    user.value.avatar = 'src/assets/img/member/user_center.png';
  } else {
    user.value.avatar = IMG_BASE_PATH + avatar;
  }
}
</script>

<style scoped>
.main-content {
  display: flex;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.sidebar {
  width: 250px;
  margin-right: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  height: fit-content;
}

.product-area {
  flex: 1;
}
</style>